package com.xywy.wjk.fragment;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.bean.WeightDataFormServer;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.util.CalendarUtil;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MD5Util;
import com.xywy.common.util.ble.common.CommonAttr;
import com.xywy.common.util.ble.util.BLEWeightScaleProvider;
import com.xywy.fwc.net.BaseParser;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.AddDevicesActivity;
import com.xywy.wjk.ScanBLEActivity;
import com.xywy.wjk.SelectBrandActivity;
import com.xywy.wjk.WjkActivity;
import com.xywy.wjk.WjkDetailActivity;
import com.xywy.wjk.WjkPopupActivity;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.dao.WeightDataDao.Properties;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.CircleView;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.TipDialog.OkayListener;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * 体重
 * 
 * @author wangwenlong
 */
public class WeightFragment extends Fragment implements OnClickListener {
	private RelativeLayout rl_top; //是否连接 
	private TextView tv_connect_state;//连接状态
	private TextView tv_connect_time; //连接时间
	private LinearLayout ll_not_connectted_prompot;
	private CircleView wjk_circle_view;
	private ImageView iv_unopen_big;
	public static final int REQUEST_DIALOG = 0x1111; //连接设备
	private BLEWeightScaleProvider utils;
	private BluetoothAdapter mBluetoothAdapter;// 蓝牙适配器。
	String TAG = "WeightFragment";
	private TipDialog dialog; // 连接提示框
	private String startName; // 设备的名字的起始部位
	private boolean isConnectedSuc; // 当前设备是否正在连接ing；
	BluetoothGattCharacteristic info_Characteristic; // 设备信息通道（获取SystemID）
	BluetoothGattService infoDataService; // 设备服务
	private byte[] currentUserWeightData1; // 当前用户重量数据1，
	private byte[] currentUserWeightData2; // 当前用户重量数据2
	private BluetoothGattCharacteristic swap_Characteristic;
	private byte[] SystemID;
	private float currentWeightData;// 体重
	private BluetoothGattService swapDataService;
	private boolean is_connect = false;
	
	private SharedPreferences sp;
	private String userid;
	
	private WeightDataDao weightDataDao; // 体重秤表dao；
	Handler mhander = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TipDialog.DIALOG_TIMER_CANCLE:
				mBluetoothAdapter.stopLeScan(mLeScanCallback);
				// 13秒扫描结束的时候，当前设备并没有连接成功，则展示当前连接失败；
				if (!isConnectedSuc) {
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							stateFail();
//							Toast.makeText(getActivity(), "连接失败"
//							, Toast.LENGTH_SHORT).show();
						}
					});
				}
				break;
			default:
				break;
			}
		};
	};
	
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			if (null != device.getName() && device.getName().startsWith(startName)) {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(!is_connect){
							is_connect = true;
							mBluetoothAdapter.stopLeScan(mLeScanCallback);
							connectDevice(device.getAddress());
						}
					}
				});
			}
		}
	};
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.weight_fragment, null);
		sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(getActivity()).getUserid();
		initDAO();
		dialog = new TipDialog(getActivity(), TipDialog.VIEW_LOADING, mhander);
		getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		initView(view);
		initBLE();
		return view;
	}
    
	private void initView(View view){
		rl_top = (RelativeLayout) view.findViewById(R.id.toprel);
		tv_connect_state = (TextView) view.findViewById(R.id.tv_connect_state);
		tv_connect_time = (TextView) view.findViewById(R.id.messageTime);
		ll_not_connectted_prompot = (LinearLayout) view.findViewById(R.id.ll_not_connectted_prompot);
		wjk_circle_view = (CircleView) view.findViewById(R.id.wjk_circle_view);
		iv_unopen_big = (ImageView) view.findViewById(R.id.iv_unopen_big);
		iv_unopen_big.setOnClickListener(this);
		ll_not_connectted_prompot.setOnClickListener(this);
		ConnectedDevice connect_device = FileUtil.getWeightDevice();
		if(connect_device.getConnect_time()>0){
			iv_unopen_big.setVisibility(View.GONE);
			showLine();
		}else {
			iv_unopen_big.setVisibility(View.VISIBLE);
			hideLine();
		}
		wjk_circle_view.setOnClickListener(this);
		setDeviceStatusAndTime();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_unopen_big:
			//现在跳转到添加设备页面 添加后返回
			Intent intent = new Intent(getActivity(),WjkPopupActivity.class);
			startActivityForResult(intent, REQUEST_DIALOG);
			break;
		case R.id.ll_not_connectted_prompot:
			scanLeDevice(true, "Xun");
			break;
		case R.id.wjk_circle_view:
			Intent detailIntent = new Intent(getActivity(), WjkDetailActivity.class);
			detailIntent.putExtra(ScanBLEActivity.USER_WEIGHT_DATA_1, currentUserWeightData1);
			detailIntent.putExtra(ScanBLEActivity.USER_WEIGHT_DATA_2, currentUserWeightData2);
			startActivity(detailIntent);
			break;

		default:
			break;
		}
	}
	
	/**
	 * 跳转到添加设备界面
	 */
	private void intentAddDevice() {
		Intent weightIntent = new Intent(getActivity(), SelectBrandActivity.class);
		weightIntent.putExtra("deviceType", "体重秤");
		startActivity(weightIntent);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("onActivityResult----wjkfragment");
		if(data != null && resultCode == Activity.RESULT_OK)
		switch (requestCode) {
		case REQUEST_DIALOG:
			int confirm = data.getIntExtra("confirm", -1);
			if(confirm == 1){
				intentAddDevice();
			}
			break;
		default:
			break;
		}
	}
	
//	private Handler observerHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			switch (msg.what) {
//			case ObserverConstants.WEIGHT_DB_MAKER:
//				/* 展示上次体重数据 */
//				if (!FragmentMainActivity.CANTOUCH)
//					return;
//				break;
//			case ObserverConstants.CHANGE_WEIGHT_MAKER:
//				// 切换为体重
//				System.out.println("开始测量体重----");
//				//这个时候开始连接蓝牙
//				scanLeDevice(true, "Xun");
//				break;
//
//			default:
//				break;
//			}
//		};
//	};
//	private DevicesObserver observer;
//	
//	void registerDBobserver() {
//		observer = new DevicesObserver(observerHandler);
//		getActivity().getContentResolver().registerContentObserver(ObserverConstants.WEIGHT_DB_CHANGE, false, observer);
//		getActivity().getContentResolver().registerContentObserver(ObserverConstants.CHANGE_WEIGHT, false, observer);
//	}
	
	
	private void initReceiver(){
		IntentFilter filter = new IntentFilter(WjkConstant.CONNECTING_WEIGHT_ACTION);
		filter.addAction(WjkConstant.GET_DEVICE);
		getActivity().registerReceiver(new ChangeReceiver(), filter);
	}
	
	class ChangeReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(WjkConstant.CONNECTING_WEIGHT_ACTION.equals(action)){
				System.out.println("现在开始体重秤的蓝牙连接----");
				scanLeDevice(true, "Xun");
			}else if (WjkConstant.GET_DEVICE.equals(action)) {
				ConnectedDevice weight_device = FileUtil.getWeightDevice();
				if(weight_device.getConnect_time()>0){
					iv_unopen_big.setVisibility(View.GONE);
					setDeviceStatusAndTime();
					if(!isConnectedSuc){
						showLine();
					}
				}
			}else if (WjkConstant.GET_DATA.equals(action)) {
				WeightData data = getLastData();
				if(data != null)
					setTaskView(data.getWeight());
			}
		}
	}
	
	/**
	 * 初始化蓝牙配置
	 */
	private void initBLE() {
		utils = BLEWeightScaleProvider.getInstance();
		utils.init(getActivity());
		mBluetoothAdapter = utils.getBLEAdatper();
		if (mBluetoothAdapter == null) {
			Toast.makeText(getParentFragment().getActivity(), "您的当前的设备不支持蓝牙通信，继续使用会出现异常情况。请关闭应用。", Toast.LENGTH_LONG).show();
		}

	}
	
	public void scanLeDevice(final boolean enable, String startName) {
		
		if (utils == null) {
			initBLE();
		}
		if (!mBluetoothAdapter.isEnabled()) {
			unOpenBleTip();
			return;
		}
		stateScaning();
		this.startName = startName;
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mhander.postDelayed(new Runnable() {
				@SuppressLint("NewApi")
				@Override
				public void run() {
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					// 13秒扫描结束的时候，当前设备并没有连接成功，则展示当前连接失败；
					if (!isConnectedSuc) {
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								stateFail();
//								Toast.makeText(getActivity(), "连接失败"
//								, Toast.LENGTH_SHORT).show();
							}
						});
					}

				}
			}, 15 * 1000);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}

	}
	
	/**
	 * 当前为打开蓝牙设备，
	 */
	private void unOpenBleTip() {
		final TipDialog dialog = new TipDialog(getActivity(), TipDialog.VIEW_TIP);
		dialog.setTitleAndContent("蓝牙未开启", "检测到你没有打开手机蓝牙，请打开后再试");
		dialog.setOkayCallback(new OkayListener() {

			@Override
			public void okay() {
				dialog.dismiss();
				Log.d(TAG, "用户未开启当前手机的蓝牙设备；");
			}
		});
		dialog.show();
	}
	
	/** 扫描中 
	 * 显示对话框
	 * */
	public void stateScaning() {
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				tv_connect_state.setVisibility(View.GONE); // 隐藏连接状态
				hideLine();// 隐藏黄线
				dialog.show(); // 展示黄线
			}
		});

	}
	
	/**
	 * 隐藏当前的黄线
	 */
	public void hideLine() {
	    ll_not_connectted_prompot.setVisibility(View.GONE);
	}

	/**
	 * 展示当前的黄线
	 */
	public void showLine() {
	    ll_not_connectted_prompot.setVisibility(View.VISIBLE);
	}
	
	/** 连接失败 */
	public void stateFail() {
		Log.e(TAG, "stateFail-----");
		is_connect = false;
		final ConnectedDevice weight_device = FileUtil.getWeightDevice();
		weight_device.setConnected(false);
		FileUtil.saveWeightDevice(weight_device);
		FragmentMainActivity.CANTOUCH = true;
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				isConnectedSuc = false;
				utils.disconnect();
				tv_connect_state.setVisibility(View.GONE); // 隐藏连接状态
				if(weight_device.getConnect_time()>0){
					showLine();// 显示黄线
					setDeviceStatusAndTime();
				}else {
					iv_unopen_big.setVisibility(View.VISIBLE);
				}
				dialog.dismiss();
			}
		});
		WeightData data = getLastData();
		if(data != null)
		setTaskView(data.getWeight());

	}
	
	/**
	 * 开始连接体重秤
	 */
	private void connectDevice(String curAddress) {
		if (utils.getConnectState() == BluetoothProfile.STATE_CONNECTED) {
			utils.disconnect();
		}
		if (null != curAddress && curAddress.length() > 0) {
			utils.connect(curAddress);
		} else {
			// 并没有连接过当前体重设备。点击跳转到设备添加页面；
			Intent intent = new Intent(getActivity(), AddDevicesActivity.class);
			startActivityForResult(intent, ResultCode.SUCCESS);
			Toast.makeText(getActivity(), "您尚未连接过当前设备，请先添加设备！", Toast.LENGTH_LONG).show();
			stateFail();
		}
	}
	
	
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BLEWeightScaleProvider.ACTION_GATT_CONNECTED.equals(action)) {
				// 连接时
				stateSuc();
			} else if (BLEWeightScaleProvider.ACTION_GATT_DISCONNECTED.equals(action)) {// 断开连接时
				stateFail();
				FragmentMainActivity.CANTOUCH = true;
			} else if (BLEWeightScaleProvider.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				/* 可以获取所有的通道 */
				try {
					getGattCharacteristics();
				} catch (Exception e) {
					Log.e(TAG, "获取当前体重秤连接时的服务与通道" + e.toString());
				}

			} else if (BLEWeightScaleProvider.ACTION_WRITE_DATA_AVAILABLE.equals(action)) {
				Log.d("weightfragment", "ACTION_WRITE_DATA_AVAILABLE");
			} else if (BLEWeightScaleProvider.ACTION_DATA_AVAILABLE.equals(action)) {
				Log.d("weightfragment", "ACTION_WRITE_DATA_AVAILABLE");
			} else if (BLEWeightScaleProvider.ACTION_SYSTEMID.equals(action)) {
				/* 获取到设备的SystemID */
				SystemID = intent.getByteArrayExtra(BLEWeightScaleProvider.EXTRA_DATA);
				if (SystemID == null || SystemID.length != 8) {
					return;
				}
				sendOrder();
//				stateSuc();
				currentWeightData = 0;
				wjk_circle_view.setProgress(currentWeightData, "可以踩上去开始测量了", "  ");
			} else if (BLEWeightScaleProvider.ACTION_WEIGHT_DATA.equals(action)) {
				byte[] weight = intent.getByteArrayExtra(BLEWeightScaleProvider.EXTRA_DATA);
				if (weight[1] == (byte) 0x07) {
					// 此时的状态是当前的重量
					FragmentMainActivity.CANTOUCH = false;
					float weights = getdata(weight[5], weight[6]) / 10;
					if (weights == 0) {
						FragmentMainActivity.CANTOUCH = true;
					}
					wjk_circle_view.setProgress(weights, "正在测量中，请保持站姿待数值稳定", "  ");
				}
				if (weight[1] == 0x11) {
					Toast.makeText(getActivity(), "数据已经稳定", Toast.LENGTH_LONG).show();
				}
				// 更新用户信息
				updateUserInfo(utils.getBluetoothGatt(), weight);

			} else if (BLEWeightScaleProvider.ACTION_READ_CHARACTERISTIC.equals(action)) {
				Log.d("weightfragment", "hha");

			}
		}

	};
	
	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(getActivity());
		weightDataDao = baseDao.getWeightDataDao();
	}
	
	/**
	 * 从蓝牙设备上传当前用户数据
	 * 
	 * @param mBluetoothGatt
	 * @param characteristic
	 */
	@SuppressLint("NewApi")
	public void updateUserInfo(BluetoothGatt mBluetoothGatt, byte[] weight) {
		Log.d("weightfragment", "开始进行上传用户信息");
		final byte[] data = weight;
		// 08 11 02 B1 02 01 00 1B B8 48 43 00 77 00 00 00 00
		// 测量成功 第二位11的时候稳定，
		if (data[0] == (byte) 0x08 && data[1] == (byte) 0x11 && data[2] == (byte) 0x02 && data[3] == (byte) 0xb1 && data[4] == (byte) 0x02 && data[5] == (byte) 0x01) {
			swap_Characteristic.setValue(CommonAttr.WeightScale.getUserInfoFromScale1);
			Log.d("weightfragment", "成功获取了第一次的用户测量数据" + swap_Characteristic.getValue());
			mBluetoothGatt.writeCharacteristic(swap_Characteristic);
			currentUserWeightData1 = data;

		} else if (data[0] == (byte) 0x08 && data[1] == (byte) 0x12 && data[2] == (byte) 0x02 && data[3] == (byte) 0xb1 && data[4] == (byte) 0x02 && data[5] == (byte) 0x02) {
			Log.d("weightfragment", "成功获取了第二次的用户测量数据" + swap_Characteristic.getValue());
			swap_Characteristic.setValue(CommonAttr.WeightScale.getUserInfoFromScale2);
			mBluetoothGatt.writeCharacteristic(swap_Characteristic);
			currentUserWeightData2 = data;
			saveDataInLocation(currentUserWeightData1, currentUserWeightData2);
		}

	}

	float weight = 0;
	float fatData = 0;
	float waterData = 0;
	float boneData = 0;
	float fatUnderSkin = 0;
	float Metabolisim = 0;
	float fatInBody = 0;
	float muscleData = 0;
	float BodyAge = 0;

	/**
	 * 将当前数据保存到本地 ；
	 * 
	 * @param currentUserWeightData12
	 * @param currentUserWeightData22
	 */
	private void saveDataInLocation(byte[] currentUserWeightData12, byte[] currentUserWeightData22) {
		if (currentUserWeightData12 != null) {
			weight = (getdata(currentUserWeightData1[11], currentUserWeightData1[12]) / 10);
			fatData = (getdata(currentUserWeightData1[13], currentUserWeightData1[14]) / 10);
			waterData = (getdata(currentUserWeightData1[15], currentUserWeightData1[16]) / 10);
		}

		if (currentUserWeightData22 != null) {
			boneData = (getdata(currentUserWeightData2[7], currentUserWeightData2[8]) / 10);
			fatUnderSkin = (getdata(currentUserWeightData2[9]) / 10);
			Metabolisim = (getdata(currentUserWeightData2[10], currentUserWeightData2[11]));
			fatInBody = (getdata(currentUserWeightData2[12], currentUserWeightData2[13]) / 10);
			muscleData = (getdata(currentUserWeightData2[14]));
			BodyAge = (getdata(currentUserWeightData2[15]));
			DecimalFormat df = new DecimalFormat("0");
			BodyAge = Float.parseFloat(df.format(BodyAge));
		}
		if (weight > 0) {
			MobclickAgent.onEvent(getActivity(), "A006");
			insertData(weight, fatData, waterData, muscleData, boneData, Metabolisim, fatUnderSkin, fatInBody, BodyAge, "state", "temp_automactily_device_identify", "temp_handly_device_identify",
					System.currentTimeMillis());
			tv_connect_time.setVisibility(View.VISIBLE);
			tv_connect_time.setText("刚刚");
			setTaskView(weight);
			float diff = getDiff();
			if (Math.abs(diff) > 1) {
				Toast.makeText(getActivity(), "数值偏差过大，若非本人数据，请在趋势图中删除该条记录", Toast.LENGTH_SHORT).show();
			}
			FragmentMainActivity.CANTOUCH = true;
			if (fatData > 0) {
				MobclickAgent.onEvent(getActivity(), "A007");
			}
		}
	}

	/**
	 * 像数据库增加数据。
	 */
	private void insertData(Float weight, Float fatData, Float waterData, Float muscleData, Float boneData, Float Metabolisim, Float fatUnderSkin, Float fatInBody, Float BodyAge, String state,
			String device_id, String hand_str, long date) {
		WeightData data = new WeightData(null, weight, fatData, waterData, muscleData, boneData, Metabolisim, fatUnderSkin, fatInBody, BodyAge,userid, state, device_id, hand_str, date);
		System.out.println("这个是insert的时候    " + new Date(date));
		weightDataDao.insert(data);
//		uploadDataToServer(data.clone());
		uploadDataToServer(getUnuploadData());
		data = null;

	}
	
	private String secret_key = "213aBc$l;@13";
	private String sort = "tizhong";
	
	private void uploadDataToServer(final List<WeightData> datas) {
//		data.setDate(data.getDate() / 1000);
		HashMap<Object, Object> params = new HashMap<Object, Object>();
		params.put("app_username", "xywy_tizhong");
//		String userid = sp.getString("userid", "");
		params.put("xywy_userid", userid);
		params.put("sort", sort);
		String dataStr = turn2ServerJsonData(datas, userid);
		Log.e("体重上传数据值", dataStr);
		params.put("data", dataStr);
		String sn = secret_key + userid + sort + dataStr + "xywy_tizhong";
		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Request.postData(new MyPaser(datas), new DataCallBack<String>() {

			@Override
			public void dataCall(String str) {
				try {
					JSONObject json = new JSONObject(str);
					int status = json.optInt("status");
					if(status ==0){
//						sp.edit()
//						.putLong("last_download_weight_time",
//								datas.get(0).getDate())
//						.commit();
					}else {
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("上传本次体重的返回值" + str);
			}
		}, "http://api.yun.xywy.com/index.php/api/setdata/data_all/", params);

	}
	
	class MyPaser extends BaseParser<String> {

		List<WeightData> datas ;

		MyPaser(List<WeightData> datas ) {
			this.datas = datas;
		}

		@Override
		public String parseJson(String result) {
			try {
				JSONObject jsonObject = new JSONObject(result);
				int status = jsonObject.getInt("status");
				if (status == 0) {
					if(datas!= null && datas.size()>0)
					sp.edit().putLong("last_download_weight_time", datas.get(0).getDate()).commit();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}
	}
	
	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(List<WeightData> datas, String userID) {
		Gson gson = new Gson();
		List<WeightDataFormServer> jsons = new ArrayList<WeightDataFormServer>();
		for (WeightData data : datas) {
			WeightDataFormServer dataFormServer = new WeightDataFormServer();
			dataFormServer.setApp_data(data.getDevice_id());
			dataFormServer.setApp_user_id("");
			float height = (float) (sp.getInt("height", 0) / 100.0);
			float bmi = weight / (height*height);
			dataFormServer.setBmidata(Math.round(bmi));
			dataFormServer.setBmrh(data.getMetabolisim());
			dataFormServer.setBodyage(data.getBodyAge());
			dataFormServer.setBone(data.getBoneData());
			dataFormServer.setDatatime(data.getDate()/1000);
			dataFormServer.setFat(data.getFatData());
			dataFormServer.setInfat(data.getFatInBody());
			dataFormServer.setMuscle(data.getMuscleData());
			dataFormServer.setSfat(data.getFatUnderSkin());
			dataFormServer.setShou_data(data.getHand_str());
			dataFormServer.setWater(data.getWaterData());
			dataFormServer.setWeight(data.getWeight());
			dataFormServer.setXywy_userid(userID);
			dataFormServer.setApp_username("xywy_tizhong");
			dataFormServer.setSort(sort);
			jsons.add(dataFormServer);
		}
		return gson.toJson(jsons);
	}
	
	public List getUnuploadData() {
		long lastSaveTime = sp.getLong("last_download_weight_time", 1000); // 最后的上传时间
		Log.e("getUnuploadData---", lastSaveTime+"");
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(userid));
		qb.orderDesc(Properties.Id);
		qb.where(Properties.Date.gt(lastSaveTime));
		return qb.list();
	}
	
	/**
	 * 获取最后一条数据；
	 */
	private WeightData getLastData() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(userid));
		qb.orderDesc(Properties.Id);
		List<WeightData> list = qb.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
	

	/**
	 * 获取差值；
	 */
	private float getDiff() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(userid));
		qb.orderDesc(Properties.Id);
		List<WeightData> list = qb.list();
		if (list != null && list.size() > 1) {
			return list.get(0).getWeight() - list.get(1).getWeight();
		} else {
			return -0.1f;
		}
	}

	void setTaskView(float weight) {
		try {
			currentWeightData = weight; // 将当前的体重数据保存在变量中，以便onResume时调用
			SharedPreferences sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
			float height = (float) (sp.getInt("height", 0) / 100.0);
			Log.e("shengao----", height + "");
			float x = (float) (weight / height / height);
			String bmiStr = "";
			if (x < 18.5) {
				bmiStr = "偏低";
			} else if (x > 24) {
				bmiStr = "偏高";
			} else {
				bmiStr = "正常";
			}
			WeightData data = getLastData();
			if (data == null)
				return;
			// float lastWeight = data.getWeight();
			float diff = getDiff();
			DecimalFormat df = new DecimalFormat("0.0");
			if (diff == -0.1f) {
				wjk_circle_view.setProgress(weight, "您的体重为" + weight + "kg", bmiStr);
			} else {
				String diffStr = "跟上次比";
				if (diff > 0) {
					diffStr += "增加了" + df.format(Math.abs(diff));
				} else if (diff < 0) {
					diffStr += "减少了" + df.format(Math.abs(diff));
				} else {
					diffStr += "没有变化";
					wjk_circle_view.setProgress(weight, "跟上次相比没有变化哦", bmiStr);
					return;
				}
				wjk_circle_view.setProgress(weight, diffStr + "kg", bmiStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 获取通道与服务的引用
	 */
	private void getGattCharacteristics() {
		infoDataService = utils.getGattService(CommonAttr.WeightScale.BLE_DEVICE_INFO_SERVICE);
		swapDataService = utils.getGattService(CommonAttr.WeightScale.BLE_SWAP_DATA_SERVICE);

		if (null == infoDataService || null == swapDataService) {
			return;
		}

		info_Characteristic = getInfoChar(infoDataService, CommonAttr.WeightScale.BLE_DEVICE_INFO_CHAR);
		swap_Characteristic = getSwapChar(swapDataService, CommonAttr.WeightScale.BLE_SWAP_DATA_CHAR);
	}
	
	private void sendOrder() {
		byte[] value = { (byte) 0x09, (byte) 0x0f, (byte) 0x02, (byte) 0xa5, SystemID[0], SystemID[1], SystemID[2], SystemID[5], SystemID[6], SystemID[7], (byte) 0x09, (byte) 0xaf, (byte) 0x1e,
				(byte) 0x01 };
		swap_Characteristic.setValue(value);
		utils.writeCharacteristic(swap_Characteristic);
	}
	
	/** 连接成功 */
	public void stateSuc() {
		is_connect = false;
		Log.e("~~~~~~~~~~~~~~~~~", "成功体重计");
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				/**
				 * 连接上后 就给他显示
				 */
				Log.e(TAG, "已经连接到设备！");
				isConnectedSuc = true;
				if (iv_unopen_big.getVisibility() == View.VISIBLE) {
					iv_unopen_big.setVisibility(View.GONE);
				}
				tv_connect_state.setVisibility(View.VISIBLE);
				hideLine();// 隐藏黄线
				dialog.dismiss();
				
				ConnectedDevice weight_device = FileUtil.getWeightDevice();
				weight_device.setConnected(true);
				weight_device.setConnect_time(System.currentTimeMillis());
				FileUtil.saveWeightDevice(weight_device);
				setDeviceStatusAndTime();
			}
		});

	}
	
	/**
	 * 处理16进制数据
	 * 
	 * @param data
	 * @return
	 */
	private float getdata(byte... data) {
		BigInteger bigNum = new BigInteger(data);
		float intNum = Float.parseFloat(bigNum.intValue() + "");
		return intNum;
	}
	
	/**
	 * 广播过滤器 蓝牙状态的处理
	 * 
	 * @return
	 */
	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_READ_CHARACTERISTIC);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_SYSTEMID);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_WEIGHT_DATA);
		intentFilter.addAction(BLEWeightScaleProvider.ACTION_WRITE_DATA_AVAILABLE);
		return intentFilter;
	}
	
	private BluetoothGattCharacteristic getInfoChar(BluetoothGattService swapDataService, String UUID) {
		BluetoothGattCharacteristic curChar = null;

		for (BluetoothGattCharacteristic chart : swapDataService.getCharacteristics()) {

			if (chart.getUuid().toString().equals(UUID)) {
				curChar = chart;
				connectPort(curChar);
			}
		}
		return curChar;
	}

	/**
	 * 设定当前的char，打开通道；
	 */
	@SuppressLint("NewApi")
	private void connectPort(BluetoothGattCharacteristic gattCharacteristic) {
		if (gattCharacteristic != null) {
			final int charaProp = gattCharacteristic.getProperties();
			if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {

				if (gattCharacteristic != null) {
					utils.setCharacteristicNotification(gattCharacteristic, false);
				}
				utils.readCharacteristic(gattCharacteristic);
			}
			utils.setCharacteristicNotification(gattCharacteristic, true);

		}
	}
	
	@SuppressLint("NewApi")
	private BluetoothGattCharacteristic getSwapChar(BluetoothGattService swapDataService, String UUID) {

		BluetoothGattCharacteristic curChar = null;
		try {
			for (BluetoothGattCharacteristic chart : swapDataService.getCharacteristics()) {

				if (chart.getUuid().toString().equals(UUID)) {
					curChar = chart;
					connectPort(curChar);
				}
			}
		} catch (Exception e) {
			// Log
		}

		return curChar;
	}
	
	/**
	 * 设置时间和状态
	 */
	private void setDeviceStatusAndTime(){
		if(isConnectedSuc){
			tv_connect_state.setText(ConnectedDevice.CONNECT_SUCCESS);
		}else {
			tv_connect_state.setText(ConnectedDevice.CONNECT_FAILED);
		}
		ConnectedDevice weight_device = FileUtil.getWeightDevice();
		if(weight_device.getConnect_time()>0){
			tv_connect_time.setText(CalendarUtil.getDiffTime(weight_device.getConnect_time()));
		}else {
			tv_connect_time.setText("");
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initReceiver();
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isConnectedSuc){
			if(WjkActivity.HOME_FLAG){
				//显示上一次的记录
			}else {
				WjkActivity.HOME_FLAG = false;
				return;
			}
		}
		WjkActivity.HOME_FLAG = false;
		WeightData data = getLastData();
		if (data == null) {
			tv_connect_time.setVisibility(View.GONE);
		} else {
			float weight = data.getWeight();
			tv_connect_time.setVisibility(View.VISIBLE);
			long dataTime = data.getDate();
			System.out.println("dataTime------" + dataTime);
			String dt = dataTime + "";
			if (dt.length() == 10) {
				dataTime *= 1000;
			}
			tv_connect_time.setText(CalendarUtil.getDiffTime(dataTime));
		}
		if(data != null)
		setTaskView(data.getWeight());
	}
}
